#pragma once

#include "common.h"
#include <string>
#include <unordered_map>

struct User
{
    User(const std::string& ip, const uint16_t& port)
        : _ip(ip), _port(port)
    {}

    std::string _ip;
    uint16_t _port;
};


class onlineUser
{
public:
    void addUser(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.insert(make_pair(id, User(ip, port)));
    }
    void delUser(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        _users.erase(id);
    }
    bool isOnline(const std::string& ip, const uint16_t& port)
    {
        std::string id = ip + "-" + std::to_string(port);
        return _users.find(id) != _users.end();
    }

    void broadcastMassage(int sockfd, const std::string& masg)
    {
        for (auto& user : _users)
        {
            struct sockaddr_in client;
            bzero(&client, sizeof(client));

            client.sin_family = AF_INET;
            client.sin_port = htons(user.second._port);
            client.sin_addr.s_addr = inet_addr(user.second._ip.c_str());

            std::string sendMasg = "[" + user.first + "] # " + masg;

            sendto(sockfd, sendMasg.c_str(), sendMasg.size(), 0, (struct sockaddr *)&client, sizeof(client));
        }
    }

private:
    std::unordered_map<std::string, User> _users;
};